package com.ttc.ssm.controller.admin;

import com.ttc.ssm.controller.common;
import com.ttc.ssm.po.User;
import com.ttc.ssm.service.admin.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by Jiarui on 2016/7/21.
 */
@Controller
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    UserService userService;

    @RequestMapping("/login")
    public String login(HttpSession session, String userName, String password,Model model) throws Exception {
        //调用service进行用户名和密码验证
        //如果验证成功，将用户信息保存到session中
        if (userName == null ||userName.equals("")){
            model.addAttribute("msg","请输入用户名！");
            return "forward:/WEB-INF/jsp/admin/login.jsp";
        }
        if (password == null || password.equals("")){
            model.addAttribute("msg","请输入密码！");
            return "forward:/WEB-INF/jsp/admin/login.jsp";
        }
        User user = userService.getUserByUsername(userName);
        if(user == null){
            model.addAttribute("msg","该用户不存在！");
            return "forward:/WEB-INF/jsp/admin/login.jsp";
        }
        if(!user.getPassword().equals(common.SHA1(user.getSalt()+common.SHA1(user.getSalt()+common.SHA1(password))))){
            model.addAttribute("msg","密码错误！");
            return "forward:/WEB-INF/jsp/admin/login.jsp";
        }
        session.setAttribute("admin_username", userName);
        session.setAttribute("admin_id",user.getUser_id());
        String url = (String) session.getAttribute("redirect_url");
        session.removeAttribute("redirect_url");
        if(url != null)
            return "redirect:"+url;
        else
            return "redirect:/admin/index/index.action";
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request) throws Exception{
        request.getSession().invalidate();
        return "admin/login";
    }

}
